﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using System.Web.Services;
using System.EnterpriseServices;


public partial class OrderCart_OrderPay : System.Web.UI.Page, ICallbackEventHandler
{
    private string _usercode;//用户ID
    private decimal _p_amt; //商品总金额



    private decimal _fare; //运费
    private decimal _shouldpay; //待支付金额



    private decimal _yue; //账户支付金额
    private decimal _finalje; //剩余需支付金额
    private string _methodmc; //剩余金额支付方式名称
    private string _methodid; //剩余金额支付方式ID
    private int _sumjf; //支付积分
    #region
    public decimal P_Amt
    {
        set { _p_amt = value; }
        get { return _p_amt; }
    }
    public decimal Fare
    {
        set { _fare = value; }
        get { return _fare; }
    }
    public decimal ShouldPay
    {
        set { _shouldpay = value; }
        get { return _shouldpay; }
    }
    public decimal YuE
    {
        set { _yue = value; }
        get { return _yue; }
    }
    public decimal FinalJE
    {
        set { _finalje = value; }
        get { return _finalje; }
    }
    public string MethodMC
    {
        set { _methodmc = value; }
        get { return _methodmc; }
    }
    public string MethodID
    {
        set { _methodid = value; }
        get { return _methodid; }
    }
    public int SumJF
    {
        set { _sumjf = value; }
        get { return _sumjf; }
    }

    public string UserCode
    {
        get { return _usercode; }
        set { _usercode = value; }
    }
    #endregion
    decimal Sum_Weight = 0;
    decimal Sum_XJ = 0;
    protected void Page_PreInit(object sender, EventArgs e)
    {
        Page.Theme = BLL.Common.GetWSThemes();
    }
    BLL.BUYPOCKETDETAIL bll_cart = new BLL.BUYPOCKETDETAIL();
    List<Model.BUYPOCKETDETAIL> BuyLists = new List<Model.BUYPOCKETDETAIL>(); //购物信息
    List<Model.PAYDETAIL> PayLists = new List<Model.PAYDETAIL>();//支会信息
    Model.V_CUSTOMER_ADDRESS address = new Model.V_CUSTOMER_ADDRESS(); //送货地址
    protected void Page_Load(object sender, EventArgs e)
    {

            Page.Title = BasePage.WebTitle;
            //LinkButton1.Visible = false;
            //LinkButton1.Attributes.Add("onclick", "ShowMast()");
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                Response.Redirect("../Users/Login.aspx");
            }
            if (int.Parse(Session["Step"].ToString()) < 3)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert(\"商品信息已经改变，请重新选择支付方式!\")", true);
                Response.Redirect("OrderPayMethod.aspx");
            }
            else
            {
                UserCode = BasePage.GetValue(0);
                if (!IsPostBack)
                {
                    Bind_RP();
                    Init_address();
                    Init_paymethod();
                }
                Session["Step"] = "4";
            }
    }
    #region 商品信息
    private void Bind_RP()
    {
        List<Model.BUYPOCKETDETAIL> lists = new List<Model.BUYPOCKETDETAIL>();
        lists = bll_cart.GetAllList(UserCode);
        foreach (Model.BUYPOCKETDETAIL buy in lists)
        {
            buy.BPD_WEIGHT = buy.BPD_WEIGHT * buy.BPD_QTY;
        }
        Repeater1.DataSource = lists;
        Repeater1.DataBind();
    }
    protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Sum_Weight += decimal.Parse(((Label)e.Item.FindControl("Lbl_Weight")).Text);
            Sum_XJ += decimal.Parse(((Label)e.Item.FindControl("Lbl_xj")).Text);
        }
        if (e.Item.ItemType == ListItemType.Footer)
        {
            lbl_Amt.Text = string.Format("{0:F}", Sum_XJ.ToString());
            lbl_Sweight.Text = string.Format("{0:F}", Sum_Weight);
            lbl_SBuyJF.Text = string.Format("{0:F}", Sum_XJ * BasePage.GetBaseBS());
        }
    }
    #endregion

    #region 地址信息
    private void Init_address()
    {
        if (Session["Transport"] != null)
        {
            address = (Model.V_CUSTOMER_ADDRESS)Session["Transport"];
            Model.TRANER tran = new Model.TRANER();
            tran = new BLL.TRANER().GetModel(address.WLCODE);
            lbl_Deliver.Text = tran.TRANER_NAME;
            Lbl_Recier.Text = address.Receiver;
            BLL.V_CUSTOMER_ADDRESS bll_address = new BLL.V_CUSTOMER_ADDRESS();
            SqlDataReader dr = bll_address.GetModel(address);
            if (dr.Read())
            {
                Lbl_Address.Text = dr["Province"].ToString() + dr["City"].ToString() + dr["Area"].ToString();
            }
            dr.Close();
            dr.Dispose();
            lbl_Post.Text = address.PostDM;
            lbl_Phone.Text = address.Tel;
            lbl_Mobile.Text = address.Mobile;
        }
        else
        {
            Response.Redirect("OrderAddress.aspx");
        }
    }
    #endregion

    #region 支付信息
    private void Init_paymethod()
    {
        if (Session["PayMethod"] != null)
        {
            string[] temp = Session["PayMethod"].ToString().Split(',');
            //temp0 P_Amt,temp1 Fare,temp 2 ShouldPay,temp3 YuE,temp4 FinalJE, temp5 MethodMC, temp6 paymethodid ,temp7 sumjf
            SP_P_Amt.Text = temp[0];
            SP_fare.Text = temp[1] == "" ? "0" : temp[1];
            SP_ShouldPay.Text = temp[2] == "" ? "0" : temp[2];
            Sp_YuE.Text = temp[3] == "" ? "0" : temp[3];
            lbl_FinalJE.Text = temp[4] == "" ? "0" : temp[4];
            PayMethodMC.Text = temp[5];
            Hid_PayMethodID.Value = temp[6];
            if (temp[7].Length > 0)
            {
                if (int.Parse(temp[7], NumberStyles.Float) > 0)
                {
                    tr_jf.Visible = true;
                    lbl_Sum_JF.Text = temp[7];
                }
                else
                {
                    tr_jf.Visible = false;
                }
            }
        }
    }
    #endregion

    #region 先读出购物车信息(有可能有促销方案时,购物信息会有所改变,所以改为在程序里传参的形式来生成订单)
    private void GetBuyInfo(string User)
    {
        BuyLists = bll_cart.GetAllList(User);
    }

    #endregion

    #region 生成订单
    string orderid;
    private void OrderDoc_Add()
    {
        decimal Order_SL = 0;//总数量



        decimal Order_ZK = decimal.Parse(BasePage.GetValue(1));//存储会员购物时折扣值.
        decimal ORDER_AMT = 0; //取订单商品明细实际金额合计  订单金额
        decimal ORDER_OFFERAMT = 0;//让利金额
        decimal ORDER_TAMT = 0;//订单总金额  金额+物流费用
        decimal ORDER_AAMT = 0;//总金额 - 让利金额，不可编辑    订单实际金额
        decimal WLFY = address.WLFY;//物流费用
        decimal ORDER_WEIGHT = 0;//商品总重量



        int BPD_ITGBUY = 0;//积分换购标志
        decimal SYJF = 0;//使用积分
        int FP = 0;//地否需要发票



        string FPTT = "";//发票抬头
        string CXFS = "";//促销方式
        string CXDH = "";//促销单号
        foreach (Model.BUYPOCKETDETAIL buyinfo in BuyLists)
        {
            Order_SL = Order_SL + buyinfo.BPD_QTY;
            ORDER_AMT = ORDER_AMT + buyinfo.BPD_AAMT;
            ORDER_OFFERAMT = ORDER_OFFERAMT;
            if (buyinfo.BPD_ITGBUY == 1)
            {
                BPD_ITGBUY = 1;
                SYJF = SYJF + buyinfo.BPD_ITG * buyinfo.BPD_QTY;
            }
            ORDER_WEIGHT = ORDER_WEIGHT + buyinfo.BPD_QTY * buyinfo.BPD_WEIGHT;
        }
        ORDER_TAMT = ORDER_AMT + WLFY;
        ORDER_AAMT = ORDER_TAMT - ORDER_OFFERAMT;

        #region 构造订单主表信息



        Model.ORDERDOC orderdoc = new Model.ORDERDOC();
        orderdoc.ORDER_CUSTOMERCODE = UserCode;
        orderdoc.ORDER_OFCODE = BasePage.OrderFrom;
        orderdoc.ORDER_DTCODE = ""; //此字段现在无用.已经移到支付明细表中
        orderdoc.ORDER_TRANERCODE = address.WLCODE;
        orderdoc.ORDER_TRANCOST = address.WLFY;
        orderdoc.ORDER_COSTNATURE = ConfigurationManager.AppSettings["COSTNATURE"];
        orderdoc.ORDER_GETER = address.Receiver;
        orderdoc.ORDER_GETERPHONE1 = address.Tel;
        orderdoc.ORDER_GETERPHONE2 = address.Mobile;
        orderdoc.ORDER_PROVINCE = address.Provice;
        orderdoc.ORDER_CITY = address.City;
        orderdoc.ORDER_AREA = address.Area;
        orderdoc.ORDER_GETADDRESS = address.Address;
        orderdoc.ORDER_GETPOSTCODE = address.PostDM;
        orderdoc.ORDER_NOTE = address.ReMark;
        orderdoc.ORDER_QTY = Order_SL;
        orderdoc.ORDER_DISC = Order_ZK;
        orderdoc.ORDER_AMT = ORDER_AMT;
        orderdoc.ORDER_OFFERAMT = ORDER_OFFERAMT;
        orderdoc.ORDER_AAMT = ORDER_AAMT;
        orderdoc.ORDER_TAMT = ORDER_TAMT;
        orderdoc.ORDER_CREATER = UserCode;
        orderdoc.ORDER_CREATEDATE = DateTime.Now;
        orderdoc.ORDER_ITGBUY = BPD_ITGBUY;
        orderdoc.ORDER_ITG = SYJF;
        orderdoc.ORDER_NINV = FP;
        orderdoc.ORDER_INVTITLE = FPTT;
        orderdoc.ORDER_OFFERTYPE = CXFS;
        orderdoc.ORDER_OFFERID = CXDH;
        orderdoc.ORDER_WEIGHT = ORDER_WEIGHT;
        orderdoc.ORDER_IsPromotion = CXDH.Length > 0 ? 1 : 0;
        orderdoc.BYZD18 = "";//标注从淘宝同步过来的订单的订单编号

        #endregion

        #region 构造支付明细表信息
        if (Session["PayMethod"] != null)
        {
            string[] temp = Session["PayMethod"].ToString().Split(',');
            //temp0 P_Amt,temp1 Fare,temp 2 ShouldPay,temp3 YuE,temp4 FinalJE, temp5 MethodMC, temp6 paymethodid ,temp7 sumjf
            //更新订单交易类型
            BLL.PAYTYPE_DEALTYPE paytd = new BLL.PAYTYPE_DEALTYPE();
            Model.PAYTYPE_DEALTYPE model_pay = new Model.PAYTYPE_DEALTYPE();
            DateTime time = DateTime.Now;

            //BLL.ORDERDOC bll_order = new BLL.ORDERDOC();
            //string orderid = bll_order.Order_Insert(orderdoc, BuyLists, PayLists, BasePage.GetBaseBS());
            if (decimal.Parse(temp[3]) > 0)  //账户余额
            {
                Model.PAYDETAIL paydetail = new Model.PAYDETAIL();
                paydetail.PD_DETAILID = "1";
                paydetail.PD_PAYTYPE = "200";
                paydetail.PD_DTCODE = paytd.GetModel("200").PD_DEALTYPECODE;
                paydetail.PD_PAYAMT = decimal.Parse(temp[3]);
                paydetail.PD_PAYDATE = time;
                paydetail.PD_DEALDATE = time;
                paydetail.PD_GETDATE = time;
                PayLists.Add(paydetail);
                

            }
            if (decimal.Parse(temp[4]) > 0) //第三方支付

            {
                Model.PAYTYPE_DEALTYPE type = new Model.PAYTYPE_DEALTYPE();
                type = paytd.GetModel(temp[6]);

                if (temp[6] == "304")
                {
                    orderdoc.ORDER_APAY = 1;
                }
                else
                {
                    Model.PAYDETAIL paydetail = new Model.PAYDETAIL();
                    paydetail.PD_DETAILID = "2";
                    paydetail.PD_PAYTYPE = temp[6];
                    paydetail.PD_DTCODE = type.PD_DEALTYPECODE;
                    paydetail.PD_PAYAMT = decimal.Parse(temp[4]);
                    paydetail.PD_PAYDATE = time;
                    paydetail.PD_ACCOUNT = new BLL.PAYTYPE().GetModel(temp[6]).PA_ACCOUNT;
                    PayLists.Add(paydetail);
                    orderdoc.ORDER_APAY = 0;
                    if (type.PD_DEALTYPECODE == "002")
                    {
                        orderdoc.ORDER_SECDEAL = 1;
                    }
                }
            }
            //if (int.Parse(temp[7],NumberStyles.Float) > 0)  //积分支付
            //{
            //    Model.PAYDETAIL paydetail = new Model.PAYDETAIL();
            //    paydetail.PD_DETAILID = "3";
            //    paydetail.PD_PAYTYPE = temp[6];
            //    paydetail.PD_PAYAMT = int.Parse(temp[7], NumberStyles.Float);
            //    paydetail.PD_PAYDATE = time;
            //    PayLists.Add(paydetail);
            //}
            //重写主表支付金额
            decimal temppayamt = 0.0M;
            foreach (Model.PAYDETAIL pd in PayLists)
            {
                temppayamt = temppayamt + pd.PD_PAYAMT;
            }
            orderdoc.ORDER_PAYAMT = temppayamt;
        }

        #endregion

        BLL.ORDERDOC bll_order = new BLL.ORDERDOC();
         orderid = bll_order.Order_Insert(orderdoc, BuyLists, PayLists, BasePage.GetBaseBS());
        if (orderid.Length > 0)
        {
            //Aduit(orderid);

            if (ConfigurationManager.AppSettings["ISPay"].ToString() == "1")  //模拟支付
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "window.location.href=\"PayResult.aspx?t=1\"", true);
            }
            else
            {
                string[] temp = Session["PayMethod"].ToString().Split(',');
                //temp0 P_Amt,temp1 Fare,temp 2 ShouldPay,temp3 YuE,temp4 FinalJE, temp5 MethodMC, temp6 paymethodid ,temp7 sumjf
                if (temp[6]!="200")
                {
                    switch (temp[6])
                    {
                        case "300": //支付宝



                            Session["Transport"] = null;
                            Session["PayMethod"] = null;
                            AliPay.ToPay(orderid, temp[4]);
                            break;
                        case "301": //网银在线
                            Session["Transport"] = null;
                            Session["PayMethod"] = null;
                            Session["OrderId"] = orderid;
                            Session["v_amount"] = temp[4];
                            Response.Redirect("../Pay/chinabank/Send.aspx");
                            break;
                        case "302": //快钱
                            Session["Transport"] = null;
                            Session["PayMethod"] = null;
                            Session["OrderId"] = orderid;
                            Session["v_amount"] = temp[4];
                            Response.Redirect("../Pay/99bill/Send.aspx");
                            break;
                        default:  //其它不用通过网上支付的.
                            Response.Redirect("PayResult.aspx?t=4&&payid=" + temp[6] + "&&orderid=" + orderid);
                            break;
                    }
                }
                else
                {
                    if (new BLL.ORDERDOC().ORDER_Update_PayStatus(orderid, temp[6], "", ""))
                    {
                        if (temp[6]=="200")
                        {
                            Aduit(orderid);
                            CAudit(orderid);
                        }
                        Response.Redirect("PayResult.aspx?t=1");
                    }
                    else
                    {
                        Response.Redirect("PayResult.aspx?t=3");
                    }

                }
            }


        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('生成订单失败');HidMask();", true);
        }
    }
    #endregion
    protected void Button1_Click(object sender, EventArgs e)
    {
        address = (Model.V_CUSTOMER_ADDRESS)Session["Transport"];
        GetBuyInfo(UserCode);
        if (address.WLCODE != "009" && address.WLCODE != "011")
        {
            if (address.WLFY == 0)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('所选物流方式的物流费用必须大于零');HidMask();", true);
            }
        }
        OrderDoc_Add();
    }
    #region 使用帐户余额生成订单时，更新逻辑
    public void Aduit(string orderid)
    {

        Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(orderid);
        DataSet ds = new BLL.ORDERDETAIL().GetOrderDetail(orderid);
        // List<Model.ORDERDETAIL> orderDetails = new BLL.ORDERDETAIL().GetList(100, 1, " OD_DETAILID ", false, " and OD_ID='" + orderId + "' ", out pageCount, out recordCount);
        IList<Model.PAYDETAIL> payDetails = new SQLServerDAL.PAYDETAIL().GetPayDetailById(orderid);
        #region 非货到付款 不含担保交易
        if (order.ORDER_APAY == 0)
        {   
            if (order.ORDER_SECDEAL == 0)
            {
                for (int i = 0; i < payDetails.Count; i++)
                {
                    //订单支付明细交易类型仅为“使用结余款”，更新该种明细记录的“到帐金额”为“支付金额


                    if (payDetails[i].PD_DTCODE == "003")
                    {
                        StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();


                        Model.V_VIPSET userInfo = new BLL.V_VIPSET().GetModel(order.ORDER_CUSTOMERCODE);
                        if (userInfo == null)
                        {
                            throw new Exception("系统内无此会员信息！");
                        }
                        Model.V_VIP_ACCOUNT userAccount = new BLL.V_VIP_ACCOUNT().GetModel(userInfo.DM);

                        if (userAccount == null)
                        {
                            strSqlToUpdateBStyleDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                            strSqlToUpdateBStyleDB.Append(userInfo.DM);
                            strSqlToUpdateBStyleDB.Append("',0)|");


                        }


                        strSqlToUpdateBStyleDB.Append("update PAYDETAIL set PD_GETAMT=");
                        strSqlToUpdateBStyleDB.Append(Convert.ToDecimal(payDetails[i].PD_PAYAMT.ToString()));
                        strSqlToUpdateBStyleDB.Append(" where pd_id='");
                        strSqlToUpdateBStyleDB.Append(orderid);
                        strSqlToUpdateBStyleDB.Append("'|");

                        //减少“可用库存”，可用库存数=原可用库存数-订单商品数量；


                        for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
                        {
                            strSqlToUpdateBStyleDB.Append("update SPKCB set SL3=SL3-");
                            strSqlToUpdateBStyleDB.Append(Convert.ToDecimal(ds.Tables[0].Rows[j]["OD_QTY"].ToString()));
                            strSqlToUpdateBStyleDB.Append(" where SPDM='");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[j]["OD_CMDCODE"].ToString());
                            strSqlToUpdateBStyleDB.Append("' and GG1DM='");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[j]["OD_COLORCODE"].ToString());
                            strSqlToUpdateBStyleDB.Append("' and GG2DM='");
                            strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[j]["OD_SIZECODE"].ToString());
                            strSqlToUpdateBStyleDB.Append("'|");

                        }
                        //打上审核标记
                        strSqlToUpdateBStyleDB.Append("update orderdoc set order_check=");
                        strSqlToUpdateBStyleDB.Append(1);
                        strSqlToUpdateBStyleDB.Append(" where ORDER_ID='");
                        strSqlToUpdateBStyleDB.Append(orderid);
                        strSqlToUpdateBStyleDB.Append("'|");





                        string stringSqlToUpdateBStyleDB = strSqlToUpdateBStyleDB.ToString();


                        char[] charToTrim = new char[] { '|' };
                        string[] strArray1 = stringSqlToUpdateBStyleDB.TrimEnd(charToTrim).Split(charToTrim);
                        if (new BLL.ORDERDETAIL().UpdateOrderDetailAndOrderMain(strArray1))
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('订单审核成功');HidMask();", true);

                        }

                    }
                }
            }

        }
        #endregion
    }
    #endregion
     #region 财务审核
  public void CAudit(string orderId) 
    {
      Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(orderId);//获取订单主表
       DataSet dstDetails = new BLL.BADETAIL().GetDetails(orderId);//
     
      bool result = false;
      //非货到付款,不含担保交易
      if (order.ORDER_APAY == 0)
      {
          if (order.ORDER_SECDEAL == 0)
          {
              DataSet ds = new BLL.PAYDETAIL().P_Order_GetProductZFMX(orderid);//获取订单支付明细
              for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
              {   //订单支付明细的交易类型为使用结余款

                  if (ds.Tables[0].Rows[i]["PD_DTCODE"].ToString() == "003")
                  {


                      decimal immediatePayAmount = 0.00M;
                      decimal accountPayAmount = 0.00M;
                      StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();
                      StringBuilder strSqlToUpdateErpDB = new StringBuilder();
                      


                      strSqlToUpdateBStyleDB.Append("update PAYDETAIL set PD_GETAMT=");
                      strSqlToUpdateBStyleDB.Append(Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"].ToString()));
                      strSqlToUpdateBStyleDB.Append(",pd_get=");
                      strSqlToUpdateBStyleDB.Append(1);
                      strSqlToUpdateBStyleDB.Append(" where pd_id='");
                      strSqlToUpdateBStyleDB.Append(orderId);
                      strSqlToUpdateBStyleDB.Append("' and PD_DETAILID='");
                      strSqlToUpdateBStyleDB.Append(ds.Tables[0].Rows[i]["PD_DETAILID"]);
                      strSqlToUpdateBStyleDB.Append("'|");
                      //支付金额
                      accountPayAmount += Convert.ToDecimal(ds.Tables[0].Rows[i]["PD_PAYAMT"]);



                      string operatorId = BasePage.GetValue(0);

                      //if (order.ORDER_PAYAMT <= immediatePayAmount + accountPayAmount)
                      //{

                      //    strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_ACHECK=1,ORDER_ACHECKER='");
                      //    strSqlToUpdateBStyleDB.Append(operatorId);
                      //    strSqlToUpdateBStyleDB.Append("',ORDER_ACHECKDATE='");
                      //    strSqlToUpdateBStyleDB.Append(DateTime.Now);
                      //    strSqlToUpdateBStyleDB.Append("',ORDER_CLEAR=1,ORDER_CLEARAMT=ORDER_CLEARAMT+");
                      //    strSqlToUpdateBStyleDB.Append(immediatePayAmount + accountPayAmount);
                      //    strSqlToUpdateBStyleDB.Append(" where ORDER_ID='");
                      //    strSqlToUpdateBStyleDB.Append(orderId);
                      //    strSqlToUpdateBStyleDB.Append("'|");

                      //}
                          
                      //else
                      //{
                      //    strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_ACHECK=1,ORDER_ACHECKER='");
                      //    strSqlToUpdateBStyleDB.Append(operatorId);
                      //    strSqlToUpdateBStyleDB.Append("',ORDER_ACHECKDATE='");
                      //    strSqlToUpdateBStyleDB.Append(DateTime.Now);
                      //    strSqlToUpdateBStyleDB.Append("',ORDER_CLEAR=1,ORDER_CLEARAMT=ORDER_CLEARAMT+");
                      //    strSqlToUpdateBStyleDB.Append(immediatePayAmount + accountPayAmount);
                      //    strSqlToUpdateBStyleDB.Append(" where ORDER_ID='");
                      //    strSqlToUpdateBStyleDB.Append(orderId);
                      //    strSqlToUpdateBStyleDB.Append("'|");
                      //}

                      if (order.ORDER_PAYAMT <= immediatePayAmount + accountPayAmount)
                      {
                          strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_ACHECK=1,ORDER_ACHECKER='");
                          strSqlToUpdateBStyleDB.Append(operatorId);
                          strSqlToUpdateBStyleDB.Append("',ORDER_ACHECKDATE='");
                          strSqlToUpdateBStyleDB.Append(DateTime.Now);
                          strSqlToUpdateBStyleDB.Append("',ORDER_CLEAR=1,ORDER_CLEARAMT=ORDER_CLEARAMT+");
                          strSqlToUpdateBStyleDB.Append(immediatePayAmount + accountPayAmount);
                          strSqlToUpdateBStyleDB.Append(",BYZD9='");
                          strSqlToUpdateBStyleDB.Append(DateTime.Now);
                          strSqlToUpdateBStyleDB.Append("' where ORDER_ID='");
                          strSqlToUpdateBStyleDB.Append(orderId);
                          strSqlToUpdateBStyleDB.Append("'|");
                      }
                      else
                      {
                          strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_ACHECK=1,ORDER_ACHECKER='");
                          strSqlToUpdateBStyleDB.Append(operatorId);
                          strSqlToUpdateBStyleDB.Append("',ORDER_ACHECKDATE='");
                          strSqlToUpdateBStyleDB.Append(DateTime.Now);
                          strSqlToUpdateBStyleDB.Append("',ORDER_CLEARAMT=ORDER_CLEARAMT+");
                          strSqlToUpdateBStyleDB.Append(immediatePayAmount + accountPayAmount);
                          strSqlToUpdateBStyleDB.Append(" where ORDER_ID='");
                          strSqlToUpdateBStyleDB.Append(orderId);
                          strSqlToUpdateBStyleDB.Append("'|");
                      }

                      Model.V_VIPSET vipset = new BLL.V_VIPSET().GetModelByGKDM(order.ORDER_CUSTOMERCODE);
                      string strUpdateVipAccountSqlString = new BLL.V_VIP_ACCOUNT().BuildUpdateVipAccountSqlString(accountPayAmount * -1, vipset.DM);
                      strSqlToUpdateBStyleDB.Append(strUpdateVipAccountSqlString);
                      strSqlToUpdateErpDB.Append(strUpdateVipAccountSqlString);

                      
                      Model.V_VIP_ACCOUNT userAccount = new BLL.V_VIP_ACCOUNT().GetModel(vipset.DM);
                      if (vipset == null)
                      {
                          throw new Exception("系统内无此会员信息！"); return;
                      }


                      if (vipset == null)
                      {
                          strSqlToUpdateBStyleDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                          strSqlToUpdateBStyleDB.Append(vipset.DM);
                          strSqlToUpdateBStyleDB.Append("',0)|");

                          strSqlToUpdateErpDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                          strSqlToUpdateErpDB.Append(vipset.DM);
                          strSqlToUpdateErpDB.Append("',0)|");
                      }



                     

                      strSqlToUpdateBStyleDB.Append("update v_vipset set BYZD13=");
                      strSqlToUpdateBStyleDB.Append(userAccount.DQJE_1 + vipset.BYZD12 - accountPayAmount);
                      strSqlToUpdateBStyleDB.Append(" WHERE DM='");
                      strSqlToUpdateBStyleDB.Append(userAccount.DM);
                      strSqlToUpdateBStyleDB.Append("'|");

                      string strInsertBalanceManagementSqlString = new BLL.BALANCEADJUST().BuildInsertMainSqlString("003",order.ORDER_ID, operatorId, operatorId, order.ORDER_CUSTOMERCODE, accountPayAmount * -1);
                      strSqlToUpdateBStyleDB.Append(strInsertBalanceManagementSqlString);




                      string stringSqlToUpdateBStyleDB = strSqlToUpdateBStyleDB.ToString();
                      string stringSqlToUpdateErpDB = strSqlToUpdateErpDB.ToString();
                      char[] charToTrim = new char[] { '|' };
                      string[] strArray1 = stringSqlToUpdateBStyleDB.TrimEnd(charToTrim).Split(charToTrim);
                      string[] strArray2 = stringSqlToUpdateErpDB.TrimEnd(charToTrim).Split(charToTrim);

                      WEB.ERP.Service webService = new WEB.ERP.Service();
                      result = webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(ConfigurationManager.AppSettings["WebServiceKey"].ToString(), strArray1, strArray2);
                      if (!result)
                      {
                          throw new Exception("财务审核失败！");

                      }
                  }
              }
              

          }
      }

                }
     #endregion

    #region ICallbackEventHandler 成员
    string result = "";
    public string GetCallbackResult()
    {
        return result;
    }

    public void RaiseCallbackEvent(string eventArgument)
    {
        if (Session["PayMethod"] != null)
        {
            string[] temp = Session["PayMethod"].ToString().Split(',');
            bool isJYK = bool.Parse(temp[8]);
            if (isJYK)
            {
                string usercode = BasePage.GetValue(0);
                DataSet ds = new BLL.BUYPOCKETDETAIL().GetDataByUser(usercode);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    Decimal value = 0.00M;
                    string spdm = "";
                    string color = "";
                    string size = "";
                    string colorName = "";
                    string sizeName = "";
                    string str1 = "";
                    string str2 = "";
                    string str3 = "";
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        spdm = row["BPD_COMMCODE"].ToString();
                        color = row["BPD_COMMCOLOR"].ToString();
                        size = row["BPD_COMMSIZE"].ToString();
                        colorName = row["COLORNAME"].ToString();
                        sizeName = row["SIZENAME"].ToString();

                        string strSql = string.Format("spdm='{0}' and GG1DM='{1}' and GG2DM='{2}' and ckdm='{3}' and kwdm='{4}' ", spdm, color, size, BasePage.GetCKDM(), BasePage.GetKWDM());
                        Decimal kykcQTY = Decimal.TryParse(new BLL.SPKCB().OC_Product_KEYONG_Stocks(strSql), out value) ? value : 0.00M;

                        //Model.COMMODITY_AUTO Commodity_Auto = new BLL..GetModel(spdm);
                        Decimal qty = Decimal.TryParse(row["BPD_QTY"].ToString(), out value) ? value : 0.00M;
                        Decimal sy = kykcQTY - qty;
                        if (kykcQTY == -1)
                        {//没有库存记录
                            str1 = str1 + spdm + "(" + colorName + "," + sizeName + ")" + ",";
                        }
                        else
                        {
                            if (qty > kykcQTY)
                            {//库存不足
                                bool Flag = false;//可补货标志

                                BLL.SYSPARAM RestockConfig = new BLL.SYSPARAM();
                                if (RestockConfig.GetRestockColorSizeConfig())
                                {//可补货控制到颜色尺码级

                                    string isRestock = new BLL.RingNor.ShangPinBL().ISReStock(spdm, color, size);
                                    if (isRestock == "1")
                                    {
                                        Flag = true;
                                    }
                                }
                                else
                                {//可补货控制到商品级

                                    string isRestock = new BLL.RingNor.ShangPinBL().ISReStock(spdm, "1", "1");
                                    if (isRestock == "1")
                                    {
                                        Flag = true;
                                    }
                                }
                                if (Flag)
                                {//可补货


                                    str2 = str2 + spdm + "(" + colorName + "," + sizeName + ")" + "只剩" + string.Format("{0:N0}", sy) + "件,";
                                }
                                else
                                { //不可补货
                                    str3 = str3 + spdm + "(" + colorName + "," + sizeName + ")" + "只剩" + string.Format("{0:N0}", sy) + "件,";
                                }
                            }

                        }

                    }
                    str1 = str1 + "|\r\n新款尚未到货，暂不能审核，请去除后继续下单，如需订购此商品请联系客服。";
                    str2 = str2 + "|\r\n但还会到货,我们会在到货后给您安排发货。是否继续生成订单?";
                    str3 = str3 + "|\r\n请返回购物袋修改数量或与客服联系!原因可能是您在放入购物袋到结账这段时间内已经被其他客户订购";
                    result = str1 + "|" + str2 + "|" + str3;
                }
            }
        }
    }

                #endregion
            }
     


